import os
import time

from file_utils import JsonOps


class ErrorData(object):
    '''错题库'''

    @staticmethod
    def __get_file_path():
        '''获取错误数据的文件路径'''
        return os.path.join(os.path.join(os.path.join(os.path.dirname(os.path.dirname(__file__)), "data"), 'error_data'), 'error_data.json')

    @classmethod
    def add_error_data(cls, key, value):
        '''
        添加拼写错误的单词到文件中
        1: 判断错误文件是否存在，如果不存在则先创建文件
        2：单词为key，value包含 错误次数 第一次错误时间 第一次错误后该单词默写的总次数
        '''
        file_path = cls.__get_file_path()
        data = JsonOps.read(file_path)
        info = data.get(key, {})
        info["sum"] = info.get('sum', 0) + 1
        info["error_num"] = info.get('error_num', 0) + 1
        info['time'] = info.get("time") if info.get("time") else time.time()
        info[key] = value
        data[key] = info
        JsonOps.write(file_path, data)

    @classmethod
    def get_error_data(cls):
        '''获取以存储的拼写错误的单词'''
        file_path = cls.__get_file_path()
        return JsonOps.read(file_path)

    @classmethod
    def add_correct_data(cls, key):
        """增加正确拼写次数 错误率低于5%时从错误库中删除"""
        file_path = cls.__get_file_path()
        data = JsonOps.read(file_path)
        info = data.get(key, {})
        info["sum"] = info.get('sum', 0) + 1
        data[key] = info

        # 错误率小于等于5%时 从错误库中删除
        sum = data.get(key).get('sum')
        error_num = data.get(key).get("error_num")
        if (error_num / sum) * 100 <= 5:
            data.pop(key)
        JsonOps.write(file_path, data)

    @classmethod
    def get_error_rate(cls, key):
        '''返回错误率'''
        file_path = cls.__get_file_path()
        data = JsonOps.read(file_path)
        info = data.get(key, {})
        sum = info.get("sum")
        error_num = info.get("error_num")
        timestamp = info.get("time", 0)
        if time.time() - timestamp < 1 * 86400:
            msg = '一天内'
        elif time.time() - timestamp < 7 * 86400:
            msg = '一周内'
        elif time.time() - timestamp < 30 * 86400:
            msg = '一月内'
        else:
            msg = "一年内"
        return f'{msg}:{int((error_num / sum) * 100)}%'
